package com.demo.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.LongDeserializer;
import org.apache.kafka.common.serialization.LongSerializer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Arrays;
import java.util.Properties;

/**
 * 测试不同group是不是都能消费到
 * 测试环境：单个kafka,集群kafka
 * 测试结果：
 *  1.不同group可以订阅后，可以消费数据，
 *  2 但是一个group的消费者数量如果大于partition数据，就最多只有partition相同数量
 * @author cxx
 * @create 2020-03-30 10:18
 **/
public class TestConsumer {


    public static void main(String[] args) {

        String groupId = System.getProperty ("group_id");
        if (groupId==null || "".equals (groupId)) {
            groupId = "110";
        }

        Properties properties = new Properties ();

        properties.setProperty (ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"ikafka:9092");
        properties.setProperty (ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
//        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class.getName());
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);

        System.out.println ("groupId:"+groupId);

        KafkaConsumer consumer =new KafkaConsumer(properties);

        consumer.subscribe (Arrays.asList ("test.sync"));
//        consumer.subscribe (Arrays.asList ("streams-wordcount-output"));
        while (true){
            ConsumerRecords<String, String>  records = consumer.poll (100);
            for (ConsumerRecord<String, String> record : records){
                System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
            }
            consumer.commitSync ();
        }
    }

}
